package me.fenglu.autodeploy;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.compressors.CompressorException;
import org.apache.commons.compress.compressors.CompressorOutputStream;
import org.apache.commons.compress.compressors.CompressorStreamFactory;

public class FileCompressor {
	
	public static byte[] tar(List<File> fileList, String compressType) {
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		TarArchiveOutputStream tarOut = null;
		ByteArrayOutputStream baos = null;
		try {
			
			byte[] buf = new byte[102400];
			baos = new ByteArrayOutputStream();
			
			CompressorOutputStream compressorOut = new CompressorStreamFactory().createCompressorOutputStream(compressType, baos);
			tarOut = new TarArchiveOutputStream(compressorOut);
			String rootPath = FileClassifier.rootPath;
			for(File file : fileList) {
				tarOut.putArchiveEntry(new TarArchiveEntry(file, file.getAbsolutePath().substring(rootPath.length()-1)));
				
				fis = new FileInputStream(file);
				bis = new BufferedInputStream(fis);
				
				int len = 0;
				while(-1 != (len = bis.read(buf))) {
					tarOut.write(buf, 0, len);
					tarOut.flush();
				}
				tarOut.closeArchiveEntry();
				bis.close();
			}
		} catch (IOException | CompressorException e) {
			e.printStackTrace();
		}finally{
			try {
				if(null != bis) {
					bis.close();
				}
				if(null != fis) {
					fis.close();
				}
				if(null != tarOut) {
					tarOut.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return baos.toByteArray();
	}
			
}
